package com.util;


import com.enums.ApiReturnCodeEnum;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class Md5Util {
    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    //静态方法，便于作为工具类
    public static String getMd5(String plainText) {
        return getMd5(plainText,false);
    }

    public static String getMd5Len32(String plainText) {
        return getMd5(plainText,true);
    }

    //静态方法，便于作为工具类
    private static String getMd5(String plainText,boolean len32) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();

            int i;

            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            if(len32){
                //32位加密
                return buf.toString();
            }else{
                //16位的加密
                return buf.toString().substring(8, 24);
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }

    }

    //获取16位的MD5 wbh 2019-5-23 新增
    private static String get16Md5(String md5) {
        if(md5==null || md5.length()!=32){
            throw new RestException(ApiReturnCodeEnum.SYSTEM_MD5_ERROR);
        }
        return md5.substring(8, 24);
    }


    /**
     * Takes the raw bytes from the digest and formats them correct.
     *
     * @param bytes the raw bytes from the digest.
     * @return the formatted bytes.
     */
    private static String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        // 把密文转换成十六进制的字符串形式
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }

    public static String encode(String str) {
        if (str == null) {
            return null;
        }
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
            messageDigest.update(str.getBytes());
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
//        //测试
//        System.out.println(com.util.Md5Util.getMd5("123456"));
//        //测试
//        System.out.println(com.util.Md5Util.getMd5("123456",true));
//        System.out.println(encode(com.util.Md5Util.getMd5("123456")));
    }

}
